const express = require('express');
const router = express.Router();
const md5=require('md5')
const User = require('../../../express-backend/models/User');
const jwt=require('jsonwebtoken')
const path = require('path');
const authenticateToken =require('../middlewares/authenticateToken');
const checkRole = require('../middlewares/checkRole');

//作家获取历史对话记录（以后搬走）
router.get('/editor/history', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    const { adminId, page = 1, limit = 20 } = req.query;
    const skip = (page - 1) * limit;

    // 查询沟通记录，按时间倒序排列
    const logs = await CommunicationLog.find({
      writerId: userId,
      adminId: adminId
    })
    .sort({ communicationTime: -1 })
    .skip(parseInt(skip))
    .limit(parseInt(limit));
    res.json({
      code: '0000',
      msg: '获取历史对话记录成功',
      data: logs
    });
  } catch (err) {
    console.error(err);
    res.json({
        code: '5000',
        msg: '服务器错误，获取历史对话记录失败',
        data: null
    });
  }
});

//作家发送消息接口（+1）
router.post('/editor/send', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.id;
    const { adminId, content } = req.body;
    if (!adminId || !content) {
      return res.json({
        code: '4000',
        msg: '参数缺失，adminId和content为必填项',
        data: null
      });
    }
    // 创建沟通记录，标记发送方为作家
    const newLog = new CommunicationLog({
      writerId: userId,
        adminId: adminId,
        senderRole: 'writer',
        content: content
    });
    await newLog.save();
    res.json({
      code: '0000',
      msg: '消息发送成功',
      data: newLog
    });
  } catch (err) {
    console.error(err);
    res.json({
        code: '5000',
        msg: '服务器错误，消息发送失败',
        data: null
    });
  }
});


// 管理员发送消息给作家
router.post('/editor/send-message', authenticateToken, async (req, res) => {
  try {
    const adminId = req.user.id;
    const { writerId, content, adminRole = 'editor' } = req.body;
    
    // 参数校验
    if (!writerId || !content) {
      return res.json({
        code: '4000',
        msg: '参数缺失，writerId和content为必填项',
        data: null
      });
    }
    
    // 创建沟通记录，标记发送方为管理员
    const newLog = new CommunicationLog({
      writerId: writerId,
      adminId: adminId,
      adminRole: adminRole,
      senderRole: 'admin', // 固定为管理员发送
      content: content
    });
    
    await newLog.save();
    
    res.json({
      code: '0000',
      msg: '消息发送成功',
      data: newLog
    });
  } catch (err) {
    console.error(err);
    res.json({
      code: '5000',
      msg: '服务器错误，消息发送失败',
      data: null
    });
  }
});

// 管理员获取与特定作家的沟通历史
router.get('/editor/communication-history', authenticateToken, async (req, res) => {
  try {
    const adminId = req.user.id;
    const { writerId, page = 1, limit = 20 } = req.query;
    const skip = (page - 1) * limit;
    
    if (!writerId) {
      return res.json({
        code: '4000',
        msg: '参数缺失，writerId为必填项',
        data: null
      });
    }
    
    const logs = await CommunicationLog.find({
      writerId: writerId,
      adminId: adminId
    })
    .sort({ communicationTime: -1 })
    .skip(parseInt(skip))
    .limit(parseInt(limit))
    .populate('writerId', 'username nickname') // 可选：填充作家信息
    .populate('adminId', 'username nickname'); // 可选：填充管理员信息
    
    res.json({
      code: '0000',
      msg: '获取沟通记录成功',
      data: logs
    });
  } catch (err) {
    console.error(err);
    res.json({
      code: '5000',
      msg: '服务器错误，获取沟通记录失败',
      data: null
    });
  }
});

module.exports = router;
